package com.itcam.socket_.udp_;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

/**
 * Author:Cammy.Wu
 * Date:2024-05-15
 * Description:加入完整异常处理方式——发送方
 */

public class SendDemo03 {
    public static void main(String[] args) {
        System.out.println("袁大帅上线了...");
        DatagramSocket datagramSocket = null;
        try {
            // 1.准备套接字：指定发送方的端口号
            datagramSocket = new DatagramSocket(8989);
            // 2.准备数据包
//        String str = "你欲何为";
            Scanner sc = new Scanner(System.in);
            System.out.print("袁天罡：");
            String str = sc.next();
            byte[] bytes = str.getBytes();

            /**
             * 需要四个参数：
             *      1.指的是传送数据转为字节数组
             *      2.字节数组的长度
             *      3.封装接收方的ip
             *      4.指定接收方的端口号
             */
            DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, InetAddress.getByName("localhost"), 8990);
            // 发送
            datagramSocket.send(datagramPacket);

            // 接受李星云的回复
            byte[] b = new byte[1024];
            DatagramPacket datagramPacket_ = new DatagramPacket(b, b.length);
            datagramSocket.receive(datagramPacket_);

            // 取出数据
            byte[] data = datagramPacket_.getData();
            String s = new String(data, 0, datagramPacket_.getLength());
            System.out.println("李星云对我说：" + s);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            datagramSocket.close();
        }

    }
}
